<template>
  <div class="bg-gradient-to-b from-sky-50 to-white rounded-lg shadow-lg p-6 overflow-hidden relative min-h-screen">
    <!-- 背景装饰 -->
    <div class="absolute top-0 right-0 w-64 h-64 bg-indigo-100 rounded-full filter blur-3xl opacity-30 -translate-y-1/2 translate-x-1/3"></div>
    <div class="absolute bottom-0 left-0 w-80 h-80 bg-sky-100 rounded-full filter blur-3xl opacity-20 translate-y-1/3 -translate-x-1/3"></div>

    <div class="relative z-10">
      <h2 class="text-xl font-semibold text-gray-800 mb-6 flex items-center">
        <span class="w-1 h-6 bg-gradient-to-b from-sky-500 to-indigo-600 rounded-full mr-3"></span>
        我的收藏
      </h2>

      <!-- 查询功能区域 -->
      <div class="mb-6 bg-white p-4 rounded-lg shadow-sm border border-sky-50">
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1.5">按关键字查询</label>
            <input
                type="text"
                v-model="searchKeyword"
                placeholder="输入合同名称或描述中的关键字"
                class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                @keyup.enter="handleSearch"
            >
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-1.5">按分类查询</label>
            <select
                v-model="searchByCategory"
                class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all appearance-none bg-white"
                @change="handleSearch"
            >
              <option value="">全部类别</option>
              <option value="劳动用工">劳动用工</option>
              <option value="商业合作">商业合作</option>
              <option value="金融借贷">金融借贷</option>
              <option value="房产交易">房产交易</option>
            </select>
          </div>
          <div class="flex items-end space-x-2">
            <button
              @click="handleSearch"
              class="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition flex-1"
            >
              <i class="fas fa-search mr-1"></i> 搜索
            </button>
            <button
              @click="resetSearch"
              class="px-4 py-2 border border-gray-300 rounded hover:bg-gray-100 transition flex-1"
            >
              <i class="fas fa-times mr-1"></i> 重置
            </button>
          </div>
        </div>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
        <!-- 收藏项循环 -->
        <div
            v-for="contract in favorites"
            :key="contract.id"
            class="border border-sky-100 bg-white rounded-lg overflow-hidden hover:shadow-lg hover:border-sky-200 transition-all duration-300 transform hover:-translate-y-1"
        >
          <!-- 模板图片 -->
          <div class="h-40 bg-gray-100">
            <img
                :src="getPreviewImageUrl(contract)"
                alt="合同模板封面"
                class="w-full h-full object-cover transition-transform duration-300 hover:scale-105"
                @error="handleImageError(contract)"
            >
          </div>

          <!-- 星标收藏按钮（可切换状态） -->
          <button
              class="absolute top-3 right-3 text-2xl cursor-pointer transition-colors z-10"
              @click="toggleFavorite(contract)"
          >
            <i :class="contract.isFavorite ? 'fas fa-star text-yellow-500' : 'far fa-star text-yellow-500 stroke-yellow-500'" />
          </button>

          <div class="p-5 pt-10"> <!-- 预留星标空间 -->
            <!-- 类别+标题+收藏+删除 -->
            <div class="flex flex-wrap justify-between items-start mb-2">
              <span class="bg-sky-50 text-sky-700 text-xs px-2 py-0.5 rounded-full mr-2 mb-2">{{ contract.category || '未分类' }}</span>
              <div v-if="isUserAdmin" class="flex items-center space-x-2">
                <button
                    @click="toggleFavorite(contract)"
                    class="text-gray-400 hover:text-yellow-500 transition-colors"
                    title="收藏/取消收藏"
                >
                  <!-- 未收藏：黄边五角星；已收藏：黄色五角星 -->
                  <i :class="contract.isFavorite ? 'fas fa-star text-yellow-500' : 'far fa-star text-yellow-500 stroke-yellow-500'" />
                  <span class="ml-1 text-xs text-gray-500">{{ contract.favoriteCount || 0 }}</span>
                </button>
                <button @click="deleteContract(contract)" class="text-gray-400 hover:text-red-500 transition-colors" title="删除模板">
                  <i class="fas fa-trash-alt"></i>
                </button>
              </div>
              <div v-else class="flex items-center space-x-2">
                <button
                    @click="toggleFavorite(contract)"
                    class="text-gray-400 hover:text-yellow-500 transition-colors"
                    title="收藏/取消收藏"
                >
                  <!-- 未收藏：黄边五角星；已收藏：黄色五角星 -->
                  <i :class="contract.isFavorite ? 'fas fa-star text-yellow-500' : 'far fa-star text-yellow-500 stroke-yellow-500'" />
                  <span class="ml-1 text-xs text-gray-500">{{ contract.favoriteCount || 0 }}</span>
                </button>
              </div>
            </div>

            <h3 class="font-medium text-gray-800 text-lg mb-2">{{ contract.name }}</h3>
            <p class="text-gray-600 text-sm mb-4 line-clamp-2">{{ contract.description || '暂无描述' }}</p>

            <!-- 统计数据：下载量、预览次数、上传时间、收藏次数 -->
            <div class="flex items-center text-xs text-gray-500 mb-4 space-x-4">
              <div class="flex items-center">
                <i class="fas fa-download mr-1 text-green-500"></i>
                <span>{{ contract.downloadCount || 0 }} 次下载</span>
              </div>
              <div class="flex items-center">
                <i class="fas fa-eye mr-1 text-blue-500"></i>
                <span>{{ contract.previewCount || 0 }} 次预览</span>
              </div>
              <div class="flex items-center">
                <i class="fas fa-star mr-1 text-yellow-500"></i>
                <span>{{ contract.favoriteCount || 0 }} 次收藏</span>
              </div>
            </div>

            <!-- 支付金额 -->
            <div class="flex items-center text-sm text-gray-700 mb-4">
              <i class="fas fa-yen-sign mr-1 text-yellow-600"></i>
              <span class="font-bold" v-if="contract.payAmount && parseFloat(contract.payAmount) > 0">¥{{ parseFloat(contract.payAmount).toFixed(2) }}</span>
              <span class="font-bold" v-else>¥9.90</span>
            </div>

            <div class="text-xs text-gray-500 mb-4">
              收藏于 {{ formatDate(contract.uploadTime) }}
            </div>

            <!-- 操作按钮组 -->
            <div class="flex justify-end space-x-3">
              <!-- 编辑按钮 -->
              <button v-if="isUserAdmin" class="text-blue-600 hover:text-blue-800 p-1.5 rounded hover:bg-blue-50 transition cursor-pointer" @click="openEditModal(contract)" title="编辑合同">
                <i class="fas fa-edit"></i>
                <span class="ml-1 text-sm">编辑</span>
              </button>

              <!-- 预览按钮 -->
              <button
                  class="text-emerald-600 hover:text-emerald-800 p-1.5 rounded hover:bg-emerald-50 transition"
                  @click="openPreview(contract)"
                  title="预览合同"
              >
                <i class="fas fa-eye"></i>
                <span class="ml-1 text-sm">预览</span>
              </button>

              <!-- 购买按钮 -->
              <button
                  class="text-gray-600 hover:text-gray-800 p-1.5 rounded hover:bg-gray-50 transition"
                  @click="purchaseContract(contract)"
                  title="购买模板"
              >
                <i class="fas fa-shopping-cart"></i>
                <span class="ml-1 text-sm">购买</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="favorites.length === 0 && !loading" class="text-center py-12 text-gray-500">
        <i class="fas fa-star text-5xl mb-4 opacity-30"></i>
        <p class="text-lg mb-2">您还没有收藏任何合同模板</p>
        <button
            class="text-blue-600 hover:text-blue-800 font-medium"
            @click="$emit('navigate', 'contract-templates')"
        >
          去浏览合同模板 →
        </button>
      </div>

      <!-- 加载中提示 -->
      <div v-if="loading" class="text-center py-12 text-gray-500">
        <i class="fas fa-spinner text-3xl mb-4 animate-spin"></i>
        <p>加载中...</p>
      </div>

      <!-- 分页控件 -->
      <div v-if="pagination.total > 0 && !loading" class="flex justify-center mt-8">
        <div class="inline-flex rounded-md shadow">
          <button
            @click="changePage(pagination.page - 1)"
            :disabled="pagination.page === 1"
            class="px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            上一页
          </button>
          <span class="px-4 py-2 border-t border-b border-gray-300 bg-white text-sm font-medium text-gray-700">
            第 {{ pagination.page }} 页 / 共 {{ Math.ceil(pagination.total / pagination.size) }} 页
          </span>
          <button
            @click="changePage(pagination.page + 1)"
            :disabled="pagination.page >= Math.ceil(pagination.total / pagination.size)"
            class="px-4 py-2 border border-gray-300 bg-white text-sm font-medium text-gray-500 hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <div v-if="showEditModal" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">
        <div class="bg-gradient-to-r from-sky-500 to-indigo-600 text-white p-4 flex justify-between items-center">
          <h3 class="text-lg font-semibold">编辑合同</h3>
          <button @click="showEditModal = false" class="hover:text-white/80 transition-colors">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <!-- 编辑表单 -->
        <div class="flex-1 p-6 overflow-y-auto space-y-6">
          <form @submit.prevent="saveContract">
            <!-- 基础信息分组 -->
            <div>
              <h4 class="text-base font-medium text-gray-700 mb-4 flex items-center">
                <span class="w-1 h-4 bg-gradient-to-b from-sky-500 to-indigo-600 rounded-full mr-2"></span>
                基础信息
              </h4>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div class="md:col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">模板名称 <span class="text-red-500">*</span></label>
                  <input
                      type="text"
                      v-model="editContract.name"
                      required
                      class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                  >
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">模板类别 <span class="text-red-500">*</span></label>
                  <select
                      v-model="editContract.category"
                      required
                      class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all appearance-none bg-white"
                  >
                    <option value="">请选择类别</option>
                    <option value="劳动用工">劳动用工</option>
                    <option value="商业合作">商业合作</option>
                    <option value="金融借贷">金融借贷</option>
                    <option value="房产交易">房产交易</option>
                  </select>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">合同文件</label>
                  <div class="flex space-x-2">
                    <input
                        type="file"
                        ref="fileInput"
                        @change="handleFileUpload"
                        accept=".pdf"
                        class="hidden"
                    >
                    <input
                        type="text"
                        :value="uploadedFile ? uploadedFile.name : (editContract.fileName || '')"
                        readonly
                        class="flex-1 px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all bg-gray-50"
                    >
                    <button type="button" @click="$refs.fileInput.click()" class="px-3 py-2 border border-sky-200 rounded-md hover:bg-sky-50 transition-colors">
                      选择文件
                    </button>
                  </div>
                  <p class="text-xs text-gray-500 mt-1">支持PDF格式，最大10MB</p>
                </div>
                <div class="md:col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">模板描述</label>
                  <textarea
                      v-model="editContract.description"
                      rows="3"
                      class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                      placeholder="简要描述模板用途、适用场景等"
                  ></textarea>
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">购买金额（元）</label>
                  <input
                      type="number"
                      v-model="editContract.payAmount"
                      min="0"
                      step="0.01"
                      class="w-full px-3 py-2 border border-sky-100 rounded-md focus:outline-none focus:ring-2 focus:ring-sky-500 focus:border-transparent transition-all"
                      placeholder="请输入购买金额"
                  >
                </div>
              </div>
            </div>

            <!-- 统计信息分组 -->
            <div>
              <h4 class="text-base font-medium text-gray-700 mb-4 flex items-center">
                <span class="w-1 h-4 bg-gradient-to-b from-sky-500 to-indigo-600 rounded-full mr-2"></span>
                统计信息（自动更新）
              </h4>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">下载量</label>
                  <input
                      type="number"
                      v-model="editContract.downloadCount"
                      readonly
                      class="w-full px-3 py-2 border border-gray-200 bg-gray-50 rounded-md cursor-not-allowed"
                  >
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">预览量</label>
                  <input
                      type="number"
                      v-model="editContract.previewCount"
                      readonly
                      class="w-full px-3 py-2 border border-gray-200 bg-gray-50 rounded-md cursor-not-allowed"
                  >
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">收藏量</label>
                  <input
                      type="number"
                      v-model="editContract.favoriteCount"
                      readonly
                      class="w-full px-3 py-2 border border-gray-200 bg-gray-50 rounded-md cursor-not-allowed"
                  >
                </div>
                <div class="md:col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-1.5">上传时间</label>
                  <input
                      type="text"
                      :value="formatDate(editContract.uploadTime)"
                      readonly
                      class="w-full px-3 py-2 border border-gray-200 bg-gray-50 rounded-md cursor-not-allowed"
                  >
                </div>
              </div>
            </div>

            <!-- 提交按钮 -->
            <div class="flex justify-end space-x-3 pt-4 border-t border-sky-50">
              <button type="button" class="px-4 py-2 border border-gray-300 rounded hover:bg-gray-100 transition" @click="showEditModal = false">
                取消
              </button>
              <button type="submit" class="px-4 py-2 bg-gradient-to-r from-sky-500 to-indigo-600 text-white rounded hover:from-sky-600 hover:to-indigo-700 transition-all shadow-sm hover:shadow">
                <i class="fas fa-save mr-1"></i> 保存修改
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 合同预览弹窗 -->
    <div v-if="showContractPreview" class="fixed inset-0 bg-black/50 flex items-center justify-center p-4 z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] flex flex-col">
        <div class="bg-gradient-to-r from-sky-500 to-indigo-600 text-white p-4 flex justify-between items-center">
          <h3 class="text-lg font-semibold">{{ currentContract.name }} - 预览</h3>
          <div class="flex items-center space-x-3">
            <button @click="toggleCollectInPreview(currentContract)" class="hover:text-white/80 transition-colors">
              <i :class="currentContract.isFavorite ? 'fas fa-star text-yellow-500' : 'far fa-star text-yellow-500 stroke-yellow-500'" />
              <span class="ml-1 text-sm">{{ currentContract.favoriteCount || 0 }}</span>
            </button>
            <button @click="closeContractPreview" class="hover:text-white/80 transition-colors">
              <i class="fas fa-times"></i>
            </button>
          </div>
        </div>
        <div class="flex-1 p-6 overflow-y-auto text-gray-700">
          <div class="text-center mb-6">
            <h4 class="text-xl font-semibold">{{ currentContract.name }}</h4>
            <p class="text-sm text-gray-500 mt-1">{{ currentContract.category || '未分类' }} | 模板编号：{{ currentContract.id }}</p>
          </div>
          <div class="prose prose-sm max-w-none mb-6">
            <p>{{ currentContract.description || '暂无描述' }}</p>
            <div class="flex justify-between items-center p-3 bg-gray-50 rounded-md">
              <div class="text-sm">
                <span class="text-gray-600">下载次数：</span>
                <span class="font-medium">{{ currentContract.downloadCount || 0 }}</span>
                <span class="mx-2">|</span>
                <span class="text-gray-600">预览次数：</span>
                <span class="font-medium">{{ currentContract.previewCount || 0 }}</span>
                <span class="mx-2">|</span>
                <span class="text-gray-600">收藏次数：</span>
                <span class="font-medium">{{ currentContract.favoriteCount || 0 }}</span>
              </div>
              <div class="text-sm text-gray-500">
                上传时间：{{ formatDate(currentContract.uploadTime) }}
              </div>
            </div>
          </div>

          <!-- PDF预览图片 -->
          <div class="mt-6">
            <h5 class="text-sm font-medium text-gray-700 mb-3">文档预览</h5>
            <div v-if="currentContract.previewUrl" class="bg-gray-100 p-4 rounded-md flex justify-center">
              <img
                :src="currentContract.previewUrl"
                alt="PDF预览图片"
                class="max-w-full max-h-[500px] object-contain"
                @error="currentContract.previewUrl = 'https://picsum.photos/id/20/800/600'"
              >
            </div>
            <div v-else class="bg-gray-100 p-6 rounded-md text-center text-gray-500">
              <i class="fas fa-exclamation-circle text-2xl mb-2"></i>
              <p>该模板暂无预览图片</p>
            </div>
          </div>

          <!-- 购买按钮 -->
          <div class="text-center mt-6">
            <button @click="purchaseContract(currentContract)" class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded transition inline-flex items-center">
              <i class="fas fa-shopping-cart mr-1"></i> 购买合同模板
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import contractApi from '@/api/contractApi';
import { ElMessage } from 'element-plus';
import { getProfileApi } from '@/api/user'; // 引入获取用户信息的API

export default {
  name: 'Favorites',
  data() {
    return {
      searchKeyword: '',
      searchByCategory: '',
      favorites: [],
      pagination: {
        page: 1,
        size: 10,
        total: 0
      },
      loading: false,
      showEditModal: false,
      showContractPreview: false,
      editContract: {
        id: null,
        name: '',
        category: '',
        description: '',
        fileId: '',
        fileName: '',
        previewUrl: '',
        downloadCount: 0,
        favoriteCount: 0,
        previewCount: 0,
        uploadTime: '',
        isFavorite: true,
        payAmount: 0
      },
      currentContract: null,
      uploadedFile: null,
      currentUser: null // 添加当前用户信息
    }
  },
  computed: {
    // 判断用户是否为管理员
    isUserAdmin() {
      // 检查currentUser是否存在以及role是否为ADMIN
      return this.currentUser && this.currentUser.role === 'ADMIN';
    }
  },
  async mounted() {
    // 获取当前用户信息
    try {
      const profileRes = await getProfileApi();
      this.currentUser = profileRes.data;
    } catch (error) {
      console.error('获取用户信息失败:', error);
    }

    this.fetchFavorites();

    // 监听收藏状态更新事件
    this.favoriteUpdateHandler = (event) => {
      const { id, isFavorite, favoriteCount } = event.detail;
      const contract = this.favorites.find(c => c.id === id);
      if (contract) {
        contract.isFavorite = isFavorite;
        contract.favoriteCount = favoriteCount;

        // 如果取消收藏，则从列表中移除
        if (!isFavorite) {
          const index = this.favorites.findIndex(c => c.id === id);
          if (index !== -1) {
            this.favorites.splice(index, 1);
          }
        }
      }
    };

    window.addEventListener('favorite-updated', this.favoriteUpdateHandler);
  },
  beforeUnmount() {
    // 清理事件监听器
    if (this.favoriteUpdateHandler) {
      window.removeEventListener('favorite-updated', this.favoriteUpdateHandler);
    }
  },
  methods: {
    // 获取预览图片URL
    getPreviewImageUrl(contract) {
      // 检查是否有预设的imgUrl
      if (contract.imgUrl) {
        // 如果imgUrl已经是完整URL，直接返回
        if (contract.imgUrl.startsWith('http')) {
          return contract.imgUrl;
        }
        // 如果是相对路径，添加基础URL
        return `http://localhost:8088${contract.imgUrl}`;
      }

      // 检查是否有合同ID，如果有则生成预览URL
      if (contract.id) {
        return `http://localhost:8088/contracts/${contract.id}/preview?t=${new Date().getTime()}`;
      }

      // 返回默认图片
      return 'https://picsum.photos/id/20/400/200';
    },

    // 处理图片加载错误
    handleImageError(contract) {
      // 直接修改属性设置默认图片
      contract.previewUrl = 'https://picsum.photos/id/20/400/200';
    },

    // 获取用户收藏列表
    async fetchFavorites() {
      this.loading = true;
      try {
        // 构建查询参数
        const params = {};

        // 只有当搜索条件不为空时才添加参数
        if (this.searchKeyword && this.searchKeyword.trim() !== '') {
          params.keyword = this.searchKeyword.trim();
        }

        if (this.searchByCategory && this.searchByCategory !== '') {
          params.category = this.searchByCategory;
        }

        console.log('发送请求参数:', params);

        // 调用API获取数据
        const response = await contractApi.getUserFavorites(params);
        console.log('收到响应:', response);

        let favoritesData = [];

        // 根据响应结构正确处理数据
        if (response && typeof response === 'object') {
          if (Array.isArray(response)) {
            // 直接是数组
            favoritesData = response;
          } else if (response.data && Array.isArray(response.data)) {
            // 在data字段中
            favoritesData = response.data;
          } else {
            // 尝试其他可能的结构
            favoritesData = response.content || response.data || [response];
          }

          // 确保favoritesData是数组
          if (!Array.isArray(favoritesData)) {
            favoritesData = [favoritesData];
          }
        } else {
          favoritesData = [];
        }

        console.log('处理后的收藏数据:', favoritesData);

        // 为每个合同获取预览图片URL
        const updatedFavorites = favoritesData.map((item) => {
          return {
            ...item,
            isFavorite: true, // 收藏页面中的合同都是已收藏的
            previewUrl: item.imgUrl ? (item.imgUrl.startsWith('http') ? item.imgUrl : `http://localhost:8088${item.imgUrl}`) : (item.id ? `http://localhost:8088/contracts/${item.id}/preview` : 'https://picsum.photos/id/20/400/200')
          };
        });

        this.favorites = updatedFavorites;
        this.pagination.total = favoritesData.length;

        console.log('最终显示的收藏列表数据:', this.favorites);
      } catch (error) {
        console.error('获取收藏列表失败:', error);
        ElMessage.error('获取收藏列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },

    // 切换星标状态
    async toggleFavorite(contract) {
      try {
        // 调用API切换收藏状态
        const response = await contractApi.toggleFavorite(contract.id, false);

        // 检查响应数据结构并正确处理
        const responseData = response.data || response;
        const favoriteCount = responseData.favoriteCount;

        if (favoriteCount === undefined) {
          throw new Error('响应数据中缺少favoriteCount字段');
        }

        // 更新本地数据
        contract.isFavorite = false;
        contract.favoriteCount = favoriteCount;

        // 从收藏列表中移除
        const index = this.favorites.findIndex(fav => fav.id === contract.id);
        if (index !== -1) {
          this.favorites.splice(index, 1);
        }

        // 触发全局事件通知其他组件更新
        const event = new CustomEvent('favorite-updated', {
          detail: {
            id: contract.id,
            isFavorite: false,
            favoriteCount: favoriteCount
          }
        });
        window.dispatchEvent(event);

        ElMessage.success('取消收藏成功');
      } catch (error) {
        console.error('取消收藏失败:', error);
        ElMessage.error('取消收藏失败: ' + (error.message || '未知错误'));
      }
    },

    // 打开编辑弹窗
    openEditModal(contract) {
      this.showEditModal = true;
      this.uploadedFile = null;
      this.editContract = { ...contract };
    },

    // 保存编辑
    async saveContract() {
      try {
        // 增强表单验证
        if (!this.editContract.name || !this.editContract.category) {
          ElMessage.error('合同名称和分类不能为空');
          return;
        }

        // 准备合同数据
        const contractData = {
          name: this.editContract.name,
          category: this.editContract.category,
          description: this.editContract.description,
          payAmount: this.editContract.payAmount || 0
        };

        // 更新合同
        let savedContract;
        if (this.uploadedFile) {
          // 带文件更新
          savedContract = await contractApi.updateContractWithFile(
            this.editContract.id,
            contractData,
            this.uploadedFile
          );
        } else {
          // 不带文件更新
          savedContract = await contractApi.updateContract(this.editContract.id, contractData);
        }

        ElMessage.success('合同更新成功');
        this.showEditModal = false;
        this.fetchFavorites();
      } catch (error) {
        this.handleError(error, '合同更新失败');
      }
    },

    // 文件上传处理
    handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;

      // 文件类型验证
      const isPDF = file.type === 'application/pdf';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isPDF) {
        ElMessage.error('只能上传PDF格式的文件！');
        return;
      }

      if (!isLt10M) {
        ElMessage.error('文件大小不能超过10MB！');
        return;
      }

      this.uploadedFile = file;
    },

    // 打开预览弹窗
    async openPreview(contract) {
      this.currentContract = { ...contract };
      this.showContractPreview = true;

      // 记录预览次数
      try {
        await contractApi.recordPreview(contract.id);
        // 更新本地预览次数
        this.currentContract.previewCount = (this.currentContract.previewCount || 0) + 1;

        // 获取预览图URL
        this.currentContract.previewUrl = this.getPreviewImageUrl(contract);
      } catch (error) {
        console.error('记录预览次数失败', error);
        // 即使记录失败也不影响预览功能
        this.currentContract.previewUrl = this.getPreviewImageUrl(contract);
      }
    },

    // 关闭预览弹窗
    closeContractPreview() {
      this.showContractPreview = false;
      this.currentContract = null;
    },

    // 预览弹窗中切换收藏状态
    async toggleCollectInPreview(contract) {
      await this.toggleFavorite(contract);
    },

    // 下载合同文件
    async downloadContract(contract) {
      try {
        // 触发文件下载 - 只需要调用这一个API，后端会自动增加下载次数
        const response = await contractApi.downloadFile(contract.id);

        // 更新本地下载次数显示
        contract.downloadCount = (contract.downloadCount || 0) + 1;

        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', contract.fileName || `contract_${contract.id}.pdf`);
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error('Download error:', error);
        // 检查是否有响应错误信息
        if (error.response && error.response.data) {
          const reader = new FileReader();
          reader.onload = () => {
            this.handleError({ message: reader.result }, '文件下载失败');
          };
          reader.readAsText(error.response.data);
        } else {
          this.handleError(error, '文件下载失败');
        }
      }
    },

    // 错误处理
    handleError(error, msg) {
      console.error(msg, error);
      let errorMessage = '未知错误';

      if (error?.response?.data) {
        // 尝试读取Blob类型的错误响应
        if (error.response.data instanceof Blob) {
          const reader = new FileReader();
          reader.onload = () => {
            try {
              const errorMsg = JSON.parse(reader.result);
              ElMessage.error(`${msg}: ${errorMsg.message || errorMsg}`);
            } catch (e) {
              ElMessage.error(`${msg}: ${reader.result || '未知错误'}`);
            }
          };
          reader.onerror = () => {
            ElMessage.error(`${msg}: 无法读取错误信息`);
          };
          reader.readAsText(error.response.data);
          return;
        }

        errorMessage = error.response.data.message || error.response.data || '未知错误';
      } else if (error?.message) {
        errorMessage = error.message;
      }

      ElMessage.error(`${msg}: ${errorMessage}`);
    },

    // 切换页码
    changePage(page) {
      if (page < 1) return;
      this.pagination.page = page;
      this.fetchFavorites();
    },

    // 统一搜索处理
    handleSearch() {
      console.log('执行搜索，关键字:', this.searchKeyword, '分类:', this.searchByCategory);
      this.pagination.page = 1;
      this.fetchFavorites();
    },

    // 重置搜索条件
    resetSearch() {
      console.log('重置搜索条件');
      this.searchKeyword = '';
      this.searchByCategory = '';
      this.pagination.page = 1;
      this.fetchFavorites();
    },

    // 购买合同模板
    async purchaseContract(contract) {
      try {
        // 先获取当前用户信息
        if (!this.currentUser) {
          const profileRes = await getProfileApi();
          this.currentUser = profileRes.data;
        }

        // 创建订单数据
        const orderData = {
          templateName: contract.name || '未命名合同',
          contractNo: contract.id || 0, // 直接使用合同模板的ID作为contractNo
          amount: contract.payAmount && parseFloat(contract.payAmount) > 0.00 ? parseFloat(contract.payAmount) : 9.9, // 从合同的payAmount字段获取价格
          customerId: this.currentUser ? this.currentUser.id : 1, // 从登录用户信息中获取真实的用户ID
          contractType: contract.category || '',
          expiryDate: this.calculateExpiryDate(new Date())
        };

        // 使用handleAddOrder方法处理订单
        this.handleAddOrder(orderData);
      } catch (error) {
        console.error('创建订单失败:', error);
        ElMessage.error('创建订单失败: ' + (error.message || '未知错误'));
      }
    },

    // 新增订单处理方法
    handleAddOrder(order) {
      const newOrder = {
        number: order.number || '',
        contractNo: order.contractNo || 0, // 确保contractNo是数字
        templateName: order.templateName || order.templateName || '未命名合同',
        amount: typeof order.amount === 'number' ? order.amount : 0,
        expiryDate: order.expiryDate || this.calculateExpiryDate(order.createdTime),
        statusCode: typeof order.status === 'number' ? order.status : 0,
        customerId: order.customerId || this.customerId,
        contractType: order.contractType || ''
      };

      try {
        const serializedOrder = JSON.stringify(newOrder);
        this.$router.push({
          path: 'orders/add',
          query: {
            order: serializedOrder,
            mode: 'add',
            t: new Date().getTime()
          }
        });
      } catch (error) {
        console.error('创建新订单失败:', error);
        ElMessage.error('创建新订单失败，请重试');
      }
    },

    // 计算到期日期 (30天后)
    calculateExpiryDate(createdTime) {
      const date = new Date(createdTime || new Date());
      date.setDate(date.getDate() + 30);
      return date.toISOString().slice(0, 19).replace('T', ' ');
    },

    // 删除合同模板
    async deleteContract(contract) {
      try {
      // 确认删除操作
      if (!window.confirm(`确定要删除合同模板 "${contract.name}" 吗？此操作不可恢复。`)) {
        return;
      }

      // 调用API删除合同
      await contractApi.deleteContract(contract.id);

      // 成功删除后更新列表
      ElMessage.success('合同模板删除成功');
      this.fetchFavorites();
      } catch (error) {
        console.error('删除合同模板失败:', error);
        ElMessage.error('删除合同模板失败: ' + (error.message || '未知错误'));
      }
    }
  }
};
</script>

<style scoped>
/* 星标按钮动画 */
.text-yellow-500 {
  transform: scale(1.1);
}

/* 弹窗样式优化 */
.custom-dialog {
  --el-dialog-background-color: rgba(255,255,255,0.92);
  backdrop-filter: blur(12px);
  border: 1px solid rgba(255,255,255,0.3);
}

/* 进度条容器 */
.absolute.inset-0.flex {
  z-index: 10;
}

/* 加载动画 */
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 确保按钮可点击 */
button {
  cursor: pointer;
}

/* 确保弹窗显示在最上层 */
.z-50 {
  z-index: 5000;
}
</style>
